package logic

import (
	"context"
	"encoding/json"
	"errors"
	"time"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"
	"laundry-service/entity"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type UserinfosaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserinfosaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserinfosaveLogic {
	return &UserinfosaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserinfosaveLogic) Userinfosave(req *types.UserinfosaveReq) (resp *types.Reply, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	user, err := l.svcCtx.Db.GetUserById(int(userId))
	if err != nil {
		return nil, err
	}

	if req.Code != "" {
		pnResp, err := l.svcCtx.MiniProgram.GetAuth().GetPhoneNumber(req.Code)
		if err != nil {
			return nil, err
		}
		if pnResp.ErrCode != 0 {
			return nil, errors.New(pnResp.ErrMsg)
		}
		phone := pnResp.PhoneInfo.PurePhoneNumber

		ub, err := l.svcCtx.Db.GetUserByMobile(phone)
		if err != nil {
			if err == gorm.ErrRecordNotFound {
				user.Mobile = phone
			} else {
				return nil, err
			}
		} else {
			if ub.ID != int(userId) {
				return nil, errors.New("该手机号已绑定过其他账号了，请联系管理员")
			}
		}

	}

	if req.Name != "" {
		user.Name = req.Name
	}
	if req.Gender != "" {
		user.Gender = req.Gender
	}
	if req.SchoolId > 0 {
		user.SchoolId = req.SchoolId
	}

	if req.Avatar != "" {
		user.Avatar = req.Avatar
	}

	err = l.svcCtx.Db.UserSave(user)
	if req.SchoolId > 0 {

		couponIdArr := []int{1, 2, 3}
		for _, couponId := range couponIdArr {
			cp, err := l.svcCtx.Db.GetCouponById(couponId)
			if err == nil {
				if cp.State == 1 {
					_, err = l.svcCtx.Db.GetUserCoupon(couponId, int(userId))
					if err == gorm.ErrRecordNotFound {
						if couponId > 0 {
							uc := new(entity.UserCoupon)
							uc.UserId = int(userId)
							uc.CouponId = couponId
							uc.State = 0
							t := time.Now().AddDate(0, 0, cp.Expired)
							uc.ExpiredAt = t
							l.svcCtx.Db.SaveUserCoupon(uc)

						}

					}
				}
			}

		}

		uv, err := l.svcCtx.Db.GetUserInviteByUserId(int(userId))
		if err == nil {
			inviteCouponId := 4

			cp, err := l.svcCtx.Db.GetCouponById(inviteCouponId)
			if err == nil {
				if cp.State == 1 {
					_, err = l.svcCtx.Db.GetUserCouponByInvitee(inviteCouponId, uv.InvitedId, int(userId))
					if err == gorm.ErrRecordNotFound {
						uc := new(entity.UserCoupon)
						uc.UserId = uv.InvitedId
						uc.CouponId = inviteCouponId
						uc.Invitee = int(userId)
						uc.State = 0
						t := time.Now().AddDate(0, 0, cp.Expired)
						uc.ExpiredAt = t
						l.svcCtx.Db.SaveUserCoupon(uc)
					}
				}
			}

		}
	}

	return
}
